package com.ybl.wallet.service.impl;

import com.ybl.wallet.entity.Transactions;
import com.ybl.wallet.mapper.TransactionsMapper;
import com.ybl.wallet.mapper.WalletMapper;
import com.ybl.wallet.service.WalletService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Date;

@Service
public class WalletServiceImpl implements WalletService {

    private WalletMapper walletMapper;
    private TransactionsMapper transactionsMapper;

    @Override
    public double getBalance(Long userId) {
        return walletMapper.getBalance(userId);
    }

    @Override
    public boolean consume(Long userId, double amount){
        Double b = walletMapper.getBalance(userId);
        boolean consume = true;
        if (b == null) {
            consume = false;
            System.out.println("用户无钱包");
        }
        if (b.compareTo(amount) < 0) {
            consume = false;
            System.out.println("余额不足");;
        }
        // 扣除用户钱包余额
        try {
            walletMapper.updateBalance(userId, amount);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Date date = new Date();

        // 添加消费交易记录
        try {
            Transactions transaction = new Transactions();
            transaction.setUserId(userId);
            transaction.setType("消费");
            transaction.setAmount(amount);
            transaction.setCreatedAt((Timestamp) date);
            transactionsMapper.insert(transaction);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return consume;
    }

    @Override
    public boolean refund(Long userId, double amount) {

        Double b1 = walletMapper.getBalance(userId);

        // 增加用户钱包余额
        try {
            walletMapper.updateBalance(userId, amount);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Date date = new Date();
        // 添加退款交易记录
        try {
            Transactions transaction = new Transactions();
            transaction.setUserId(userId);
            transaction.setType("退款");
            transaction.setAmount(amount);
            transaction.setCreatedAt((Timestamp) date);
            transactionsMapper.insert(transaction);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Double b2 = walletMapper.getBalance(userId);

        if (b2 - b1 == amount){
            return true;
        }
        return false;
    }



}
